package com.boyuan.huijiaoyu;

import java.util.ArrayList;
import java.util.List;

import com.boyuan.aboutcase.AddCaseMembersActivity;
import com.boyuan.aboutcase.CaseDetailActivity;
import com.example.contactfragment.ContactGroupService;
import com.example.contactfragment.ContactService;
import com.example.contactfragment.GroupMember;
import com.example.contactfragment.HomeContactMyCaseGroupActivity;
import com.example.contactfragment.HomeContactMyGroupActivity;
import com.example.contactfragment.LognUser;
import com.example.huanxin.GroupDetailActivity;
import com.example.newfragment.DetailPerson;
import com.example.newfragment.HomeService;
import com.magicsoft.app.entity.CaseDetailEntity;
import com.magicsoft.app.helper.SharePreferenceHelper;
import com.magicsoft.app.helper.ToastHelper;
import com.magicsoft.app.wcf.CaseService;
import com.magicsoft.app.wcf.listener.GetMultilParamsListener;
import com.magicsoft.app.wcf.listener.GetOneRecordListener;
import com.magicsoft.app.wcf.listener.PostRecordResponseListener;
import com.magicsoft.constant.Constant;
import com.magicsoft.weitown.ui.CustomDialog;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.ttcaca.cas.android.client.utils.Helper;

import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceActivity.Header;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class CaseGroupDetailActivity extends Activity implements OnClickListener{
	
	private String groupId;
	private String groupName;
	private ContactGroupService contactgroupService;
	ArrayList<GroupMember> groups = new ArrayList<GroupMember>();
	ArrayList<String> phonelist = new ArrayList<String>();
	ArrayList<String> usernamelist = new ArrayList<String>();
	ArrayList<String> memberlist = new ArrayList<String>();
	private GridView gridview;
	private MyAdapter adapter;
	boolean isgetGroupMember = false;
	private String yonghu;
	private Button btn_tuiqun;
	private DisplayImageOptions options;
	private ImageLoader imageLoader;
	boolean isdel = false;
	boolean isclick = true;
	private String groudMemberID;
	boolean isgetidOK = false;
	private ContactService contactService;
	private DetailPerson homeContactDetailEntity;
	private String yonghuID;
	int nun;
	boolean isreqok = false;
	private TextView group_name;
	boolean isdelok = false;
	private TextView tv_title;
	private String caseid;
	private CaseService caseService;
	private String realname;
	private HomeService homeService;
	private CaseDetailEntity caseDetailEntity;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_case_group_detail);
		SharedPreferences sp = getSharedPreferences("a.xml", 0);
		yonghu = sp.getString("username","");
		yonghuID = sp.getString("id", "");
		realname = sp.getString("realname", "");
		Intent intent = getIntent();
		groupId = intent.getStringExtra("groupId");
		groupName = intent.getStringExtra("groupName");
		caseid = intent.getStringExtra("caseid");
		getCaseDetailInfo2();
		btn_tuiqun = (Button) findViewById(R.id.btn_tuiqun);
		tv_title = (TextView) findViewById(R.id.group_name123);
//		getGroupMemberCache();
		getGroupMember();
		initUI();
	}
	
	private void initUI() {
		group_name = (TextView) findViewById(R.id.group_name);
		findViewById(R.id.lay_groupname).setOnClickListener(this);
		group_name.setText(groupName);
		gridview = (GridView) findViewById(R.id.gridView1);
		adapter = new MyAdapter();
		gridview.setAdapter(adapter);
		gridview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, final int arg2,
					long arg3) {
				Button btn_delmember = (Button) arg1.findViewById(R.id.imag_delgroupmember);
				ImageView iamg_tou = (ImageView) arg1.findViewById(R.id.imag_tou);
				if(arg2 <= phonelist.size()-1){
					if(isdel == true){
						
					}else{
						getid(phonelist.get(arg2));
						new Handler().postDelayed(new Runnable() {
							
							@Override
							public void run() {
								if(isgetidOK == true){
									getContactDetail(groudMemberID);
									return;
								}else{
									new Handler().postDelayed(this, 1000);
								}
							}
						}, 1000);
						finish();
					}
				}else if(arg2 == phonelist.size()){
					if(caseDetailEntity != null){
						Intent intent = new Intent();
						intent.setClass(CaseGroupDetailActivity.this, AddCaseMembersActivity.class);
						intent.putExtra("caseDetailEntity", caseDetailEntity);
						startActivityForResult(intent, 111);
					}else{
						Helper.showToast(CaseGroupDetailActivity.this, "获取case信息失败");
					}
				}else{
					isdel = !isdel;
					adapter.notifyDataSetChanged();
				}
			}
		});
		
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(data!=null){
			if(requestCode==111&&resultCode==222){
//				phonelist.clear();
//				usernamelist.clear();
//				getGroupMember();
//				adapter.notifyDataSetChanged();
				try {
					Thread.sleep(1000);
					getGroupMember();
					adapter.notifyDataSetChanged();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}else if(requestCode==3&&resultCode==4){
				phonelist.clear();
				usernamelist.clear();
				getGroupMember();
			}else if(requestCode==5&&resultCode==6){
				String groupname1 = data.getStringExtra("groupname1");
				group_name.setText(groupname1);
			}
		}
	}
	
	class MyAdapter extends BaseAdapter{
		int i = 0;
		@Override
		public int getCount() {
			if(nun == 0){
//				i = phonelist.size()+2;
				i = phonelist.size()+1;
			}else if(nun == 1){
				i = phonelist.size()+1;
			}else{
				i = 0;
			}
			return i;
		}

		@Override
		public Object getItem(int arg0) {
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			return 0;
		}

		@Override
		public View getView(final int arg0, View arg1, ViewGroup arg2) {
			View inflate = getLayoutInflater().inflate(R.layout.grid_member, null);
			final TextView tv = (TextView) inflate.findViewById(R.id.textView1);
			ImageView imag_tou = (ImageView) inflate.findViewById(R.id.imag_tou);
			imageLoader = ImageLoader.getInstance();
			options = new DisplayImageOptions.Builder()
			.showImageOnLoading(R.drawable.default_header)
			.showImageForEmptyUri(R.drawable.default_header)
			.showImageOnFail(R.drawable.default_header).cacheInMemory(true)
			.cacheOnDisc(true).considerExifParams(true)
			.build();
			final Button imag_del = (Button) inflate.findViewById(R.id.imag_delgroupmember);
			if(arg0<=phonelist.size()-1){
				String uri = Constant.photourl1 + phonelist.get(arg0);
				imageLoader.displayImage(uri, imag_tou, options);
//				tv.setText(phonelist.get(arg0));
				tv.setText(usernamelist.get(arg0));
				if(phonelist.get(arg0).equals(yonghu)){
					
				}else{
					if(isdel == true){
//						imag_del.setVisibility(View.VISIBLE);
//						gridview.setClickable(false);
//						gridview.setPressed(false);
//						gridview.setEnabled(false);
//						imag_del.setOnClickListener(new OnClickListener() {
//							@Override
//							public void onClick(View v) {
////								delGroupMember(groupId, phonelist.get(arg0),arg0);
//								
//							}
//						});
						imag_del.setVisibility(View.GONE);
					}else{
					imag_del.setVisibility(View.GONE);
//					gridview.setClickable(true);
//					gridview.setPressed(true);
//					gridview.setEnabled(true);
					}
				}
			}else if(arg0 == phonelist.size()){
				imag_tou.setImageResource(R.drawable.tianjia);
				tv.setVisibility(View.GONE);
			}else{
				imag_tou.setVisibility(View.GONE);
				tv.setVisibility(View.GONE);
//				imag_tou.setImageResource(R.drawable.smiley_minus_btn_pressed);
//				tv.setText("");
//				for(int i=0;i<groups.size();i++){
//					if(groups.get(i).getMember()==null){
//						if(groups.get(i).getOwner().toString().equals(yonghu)){
//							imag_tou.setVisibility(View.VISIBLE);
//						}
//					}else{
//						if(groups.get(i).getMember().toString().equals(yonghu)){
//							imag_tou.setVisibility(View.GONE);
//							
//						}
//					}
//				}
			}
			return inflate;
		}
		
	}
	
	/**
	 * 点击退出群组按钮
	 */
	public void exitGroup(View view) {
		for(int i=0;i<groups.size();i++){
			if(groups.get(i).getMember()==null){
				if(groups.get(i).getOwner().toString().equals(yonghu)){
					Helper.showToast(CaseGroupDetailActivity.this, "创建者不能取消关注");
				}
			}else{
				if(groups.get(i).getMember().toString().equals(yonghu)){
					exitCase();
				}
			}
		}
	}
	

	
//	public void delcase(){
//		if (caseService == null) {
//			caseService = new CaseService(this);
//		}
//		caseService.ChangeCaseDetail(yonghuID, caseid, groupName, groupName, "5618bd56bedd324e02543a04", "3", "3", yonghuID, realname, new PostRecordResponseListener() {
//			
//			@Override
//			public void onFinish(String succString) {
//				Intent intent3 = new Intent();
//				intent3.setAction(Constant.DELETE_HOMELIST);
//				sendBroadcast(intent3);
//			}
//			
//			@Override
//			public void onFailed(String failString) {
//				
//			}
//		});
//	}
	
	private void exitCase() {
		final CustomDialog dialog = new CustomDialog(this,
				R.style.qr_dialog);
		dialog.show();
		// 标题
		TextView tv_title = (TextView) dialog.findViewById(R.id.dialog_title);
		tv_title.setText("确定取消关注");
		// 内容
		TextView tv_content = (TextView) dialog
				.findViewById(R.id.dialog_content);
		tv_content.setVisibility(View.INVISIBLE);
		tv_content.setText("");
		// 右上角取消
		ImageView imag_cancel = (ImageView) dialog
				.findViewById(R.id.dialog_img_cancel);
		imag_cancel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.cancel();
			}
		});
		// 确定按钮
		Button btn_ok = (Button) dialog.findViewById(R.id.dialog_button_ok);
		btn_ok.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.cancel();
				exitcase();
			}
		});
		// 取消按钮
		Button btn_cancel = (Button) dialog
				.findViewById(R.id.dialog_button_cancel);
		btn_cancel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.cancel();
			}
		});
	}
	
	public void exitcase(){
		if (caseService == null) {
			caseService = new CaseService(CaseGroupDetailActivity.this);
		}
		caseService.CancelAttention("1", caseid, yonghuID, realname, new PostRecordResponseListener() {
			
			@Override
			public void onFinish(String succString) {
				Intent intent3 = new Intent();
				intent3.setAction(Constant.EXITCASE);
				sendBroadcast(intent3);
			}
			
			@Override
			public void onFailed(String failString) {
				
			}
		});
	}
	
	private void getGroupMemberCache(){
		groups.clear();
		phonelist.clear();
		usernamelist.clear();
		ArrayList<GroupMember> groupmemberlist = SharePreferenceHelper.getGroupsDetail(CaseGroupDetailActivity.this, yonghuID, groupId);
		if(groupmemberlist.size()>0){
			groups.addAll(groupmemberlist);
			tv_title.setText("聊天信息("+groups.size()+")");
			for(int i=0;i<groups.size();i++){
				if(groups.get(i).getMember()==null){
					phonelist.add(groups.get(i).getOwner());
					if(groups.get(i).getOwner().toString().equals(yonghu)){
						btn_tuiqun.setText("退 出 case 群");
						nun = 0;
					}
				}else{
					phonelist.add(groups.get(i).getMember());
					if(groups.get(i).getMember().toString().equals(yonghu)){
						btn_tuiqun.setText("退 出 case 群");
						nun = 1;
					}
				}
				usernamelist.add(groups.get(i).getUsername());
			}
		}
	}
	
	private void getGroupMember() {
		if (contactgroupService == null) {
			contactgroupService = new ContactGroupService(this);
		}
		contactgroupService.getGroupMember(groupId,
				new GetOneRecordListener<List<GroupMember>>() {

			@Override
			public void onFinish(List<GroupMember> data) {
				groups.clear();
				phonelist.clear();
				usernamelist.clear();
				if (data != null && data.size() > 0) {
					Log.e("data123465", data.toString());
					groups.addAll(data);
					tv_title.setText("聊天信息("+groups.size()+")");
					SharePreferenceHelper.saveGroupsDetail(CaseGroupDetailActivity.this, yonghuID, groupId, data);
					for(int i=0;i<groups.size();i++){
						if(groups.get(i).getMember()==null){
							phonelist.add(groups.get(i).getOwner());
							if(groups.get(i).getOwner().toString().equals(yonghu)){
								btn_tuiqun.setText("退 出 case 群");
								nun = 0;
							}
						}else{
							phonelist.add(groups.get(i).getMember());
							if(groups.get(i).getMember().toString().equals(yonghu)){
								btn_tuiqun.setText("退 出 case 群");
								nun = 1;
							}
						}
						usernamelist.add(groups.get(i).getUsername());
					}
				}
				isreqok = true;
				adapter.notifyDataSetChanged();
			}

			@Override
			public void onFailed(String Message) {
				ToastHelper.showMsg(CaseGroupDetailActivity.this, Message, false);
			}
		});
	}
	
	//通过账号获取唯一id
	public void getid(String username){
		if (contactgroupService == null) {
			contactgroupService = new ContactGroupService(this);
		}
		
		contactgroupService.getuUserid(username, new GetMultilParamsListener() {
			

			@Override
			public void onFinish(Object... params) {
				if(params != null){
					LognUser user = (LognUser) params[0];
					groudMemberID = user.getId();
					isgetidOK = true;
				}
			}
			
			@Override
			public void onFailed(String Message) {
				Toast.makeText(CaseGroupDetailActivity.this, Message, Toast.LENGTH_SHORT).show();
			}
		});
	}
	
	//获取联系人详情
	private void getContactDetail(final String groupmemberid) {

		if (contactService == null) {
			contactService = new ContactService(getApplicationContext());
		}

		contactService.getContactdetail(yonghuID, groupmemberid,
				new GetOneRecordListener<DetailPerson>() {

					@Override
					public void onFinish(DetailPerson data) {
						homeContactDetailEntity = data;
						if(homeContactDetailEntity.getIs_common().equals("1")||homeContactDetailEntity.getIs_favorite().equals("1")){
							Intent intent = new Intent(CaseGroupDetailActivity.this,HomeContactDeail2Activity.class);
							intent.putExtra("uid", homeContactDetailEntity.getUid());
							intent.putExtra("homeContactDetailEntity", homeContactDetailEntity);
							intent.putExtra("titleback", tv_title.getText().toString().trim());
							startActivity(intent);
//							finish();
						}else{
							Intent intent = new Intent(CaseGroupDetailActivity.this,HomeContactDeail1Activity.class);
//							intent.putExtra("realname", homeContactDetailEntity.getRealname());
//							intent.putExtra("sex", homeContactDetailEntity.getSex());
//							intent.putExtra("account_mobile", homeContactDetailEntity.getAccount_mobile());
//							intent.putExtra("mobile", homeContactDetailEntity.getMobile());
							intent.putExtra("homeContactDetailEntity", homeContactDetailEntity);
							intent.putExtra("yonghuID", yonghuID);
							intent.putExtra("uid", groupmemberid);
							intent.putExtra("titleback", tv_title.getText().toString().trim());
							startActivity(intent);
//							finish();
						}

					}

					@Override
					public void onFailed(String Message) {
						ToastHelper.showMsg(CaseGroupDetailActivity.this,
								Message, false);
					}
				});
	}
	
	public void back(View view) {
		setResult(RESULT_OK);
		finish();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.case_group_detail, menu);
		return true;
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.lay_groupname:
//			changeGroupname();
			break;

		default:
			break;
		}
	}
	
	private void changeGroupname() {
		Intent intent = new Intent(CaseGroupDetailActivity.this,ChangeGroupnameActivity.class);
		String groupname = group_name.getText().toString().trim();
		intent.putExtra("groupname", groupname);
		intent.putExtra("groupId", groupId);
		intent.putExtra("caseid", caseid);
		intent.putExtra("yonghuID", yonghuID);
		intent.putExtra("realname", realname);
		startActivityForResult(intent, 5);
	}
	
	private void getCaseDetailInfo2() {
		if (homeService == null) {
			homeService = new HomeService(this);
		}
		homeService.getCaseAndIm(caseid,
				new GetMultilParamsListener() {

					@Override
					public void onFinish(Object... params) {
						caseDetailEntity = (CaseDetailEntity) params[0];
					}

					@Override
					public void onFailed(String Message) {
						ToastHelper.showMsg(CaseGroupDetailActivity.this, Message,
								false);
					}
				});
	}
	
}
